import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/song.dart';

class FavoritesService {
  static const String _favoritesKey = 'favorites';
  
  // 收藏状态改变的回调函数列表
  static final List<VoidCallback> _listeners = [];
  
  /// 添加监听器
  static void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }
  
  /// 移除监听器
  static void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }
  
  /// 通知所有监听器
  static void _notifyListeners() {
    for (final listener in _listeners) {
      listener();
    }
  }

  /// 添加歌曲到收藏夹
  static Future<void> addToFavorites(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      // 转换为Song对象列表
      List<Song> favorites = favoritesJson
          .map((json) => Song.fromJson(jsonDecode(json)))
          .toList();
      
      // 检查是否已经收藏
      bool alreadyExists = favorites.any((s) => 
          s.effectiveId == song.effectiveId && s.source == song.source);
      
      if (!alreadyExists) {
        // 添加到收藏夹开头
        favorites.insert(0, song);
        
        // 保存到SharedPreferences
        final updatedFavoritesJson = favorites
            .map((song) => jsonEncode(song.toJson()))
            .toList();
        
        await prefs.setStringList(_favoritesKey, updatedFavoritesJson);
        
        // 通知监听器
        _notifyListeners();
      }
    } catch (e) {
      print('Error adding to favorites: $e');
    }
  }

  /// 从收藏夹移除歌曲
  static Future<void> removeFromFavorites(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      List<Song> favorites = favoritesJson
          .map((json) => Song.fromJson(jsonDecode(json)))
          .toList();
      
      favorites.removeWhere((s) => 
          s.effectiveId == song.effectiveId && s.source == song.source);
      
      final updatedFavoritesJson = favorites
          .map((song) => jsonEncode(song.toJson()))
          .toList();
      
      await prefs.setStringList(_favoritesKey, updatedFavoritesJson);
      
      // 通知监听器
      _notifyListeners();
    } catch (e) {
      print('Error removing from favorites: $e');
    }
  }

  /// 获取收藏列表
  static Future<List<Song>> getFavorites() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      return favoritesJson
          .map((json) => Song.fromJson(jsonDecode(json)))
          .toList();
    } catch (e) {
      print('Error getting favorites: $e');
      return [];
    }
  }

  /// 检查歌曲是否已收藏
  static Future<bool> isFavorite(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      List<Song> favorites = favoritesJson
          .map((json) => Song.fromJson(jsonDecode(json)))
          .toList();
      
      return favorites.any((s) => 
          s.effectiveId == song.effectiveId && s.source == song.source);
    } catch (e) {
      print('Error checking if favorite: $e');
      return false;
    }
  }

  /// 清空收藏夹
  static Future<void> clearFavorites() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_favoritesKey);
      _notifyListeners();
    } catch (e) {
      print('Error clearing favorites: $e');
    }
  }

  // ===== 导入 / 导出 =====
  static Future<String?> exportFavoritesToFile(String filePath) async {
    try {
      final favorites = await getFavorites();
      final jsonStr = jsonEncode(favorites.map((s) => s.toJson()).toList());
      final file = File(filePath);
      await file.writeAsString(jsonStr);
      return filePath;
    } catch (e) {
      print('Error exporting favorites: $e');
      return null;
    }
  }

  static Future<int> importFavoritesFromFile(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) return 0;
      final content = await file.readAsString();
      final List<dynamic> arr = jsonDecode(content);
      final importedSongs = arr.map((j) => Song.fromJson(j)).toList();

      // 加载现有收藏
      final prefs = await SharedPreferences.getInstance();
      final existingJson = prefs.getStringList(_favoritesKey) ?? [];
      final existing = existingJson.map((json) => Song.fromJson(jsonDecode(json))).toList();

      // 将导入的歌曲按 key 映射，便于覆盖与去重
      String keyOf(Song s) => '${s.source}::${s.effectiveId}';
      final Map<String, Song> importedByKey = {
        for (final s in importedSongs) keyOf(s): s,
      };

      final Set<String> existingKeys = existing.map(keyOf).toSet();

      // 覆盖：用导入版本替换现有同 key 歌曲
      for (int i = 0; i < existing.length; i++) {
        final k = keyOf(existing[i]);
        final imported = importedByKey[k];
        if (imported != null) {
          existing[i] = imported;
          importedByKey.remove(k);
        }
      }

      // 追加：将剩余导入歌曲（现有列表中不存在）附加到末尾
      for (final entry in importedByKey.entries) {
        if (!existingKeys.contains(entry.key)) {
          existing.add(entry.value);
        }
      }

      // 保存与通知
      final updatedJson = existing.map((s) => jsonEncode(s.toJson())).toList();
      await prefs.setStringList(_favoritesKey, updatedJson);
      _notifyListeners();
      return importedSongs.length;
    } catch (e) {
      print('Error importing favorites: $e');
      return 0;
    }
  }
}